<template>
  <div class="app-registry__step-two">
    <div class="app-registry__step-two__content">
      <div class="app-registry__step-two__content__input">
        <input v-model="code" type="text" placeholder="请输入短信的验证码">
        <button :disabled="disabledcode" @click="sendCode">
          <span>{{ text }}</span>
        </button>
      </div>
      <button :disabled="handlecode" @click="handleCheckCode" class="app-registry__step-two__content__button">下一步</button>
    </div>
  </div>
</template>
<script>
import { postCheckCodeApi, postSendPhoneApi } from '@/api/haigou'
import Vue from 'vue'
import { Toast } from 'vant'

Vue.use(Toast)
export default {
  name: 'AppRegistryStepTwo',
  props: ['tel'],
  data () {
    return {
      code: '',
      disabledcode: true,
      time: 5,
      text: '5s后重新获取'
    }
  },
  computed: {
    handlecode () {
      return !/^\d{5}$/.test(this.code)
    }
  },
  methods: {
    async sendCode () {
      try {
        const res = await postSendPhoneApi(this.tel)
        Toast(`${res}`)
        this.text = '5s后重新获取'
        this.disabledcode = true
        this.timer = setInterval(() => {
          this.time--
          if (this.time <= 0) {
            this.text = '获取验证码'
            this.disabledcode = false
            this.time = 5
            clearInterval(this.timer)
          } else {
            this.text = this.time + 's后重新获取'
            this.disabledcode = true
          }
        }, 1000)
      } catch (error) {}
    },
    async handleCheckCode () {
      try {
        await postCheckCodeApi(this.tel, this.code)
        this.$router.push({ name: 'stepthree', params: { tel: this.tel } })
      } catch (error) {
        if (error.message === '10007') {
          Toast('验证码错误!')
        }
      }
    }
  },
  mounted () {
    this.sendCode()
  }
}
</script>
<style lang="scss" scoped>
.app-registry__step-two {
  &__content {
    padding: 0.16rem .35rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    &__input {
      width: 100%;
      height: 50px;
      margin: 20px 0;
      border: none;
      background: rgb(240, 240, 240);
      border-radius: 15px;
      padding: 0 20px;
      margin-top: 0;
      display: flex;
      justify-content: space-between;
      button {
        border: none;
        span {
          color: rgb(84, 167, 250);
          font-weight: 700;
        }
      }
      button:disabled {
        span {
          color: rgb(181, 218, 255);
        }
      }
      input {
        border: none;
        background: none;
      }
    }
    &__button {
      width: 100%;
      height: 50px;
      border-radius: .4rem;
      border: none;
      background: rgb(84, 167, 250);
      font-size: 18px;
      color: white;
    }
    &__button:disabled {
      background: rgb(181, 218, 255);
    }
  }
}
</style>
